const TIME_ELEMENT = document.getElementById('time')
const BEST_ELEMENT = document.getElementById('best')

function getTime(time) {
	return Math.floor(time / 60000).toFixed() + ':' + Math.floor(time / 10000 % 6).toFixed() + Math.floor(time / 1000 % 10).toFixed() + '.' + Math.floor(time / 100 % 10).toFixed() + Math.floor(time / 10 % 10).toFixed() + Math.floor(time % 10).toFixed()
}

var board = null
var game = null
var inGame = false
var startTime
var time
var bestTime = localStorage.getItem('best')
if (bestTime)
	bestTime = parseInt(bestTime)
else
	bestTime = 599999
BEST_ELEMENT.innerHTML = getTime(bestTime)
var recordTimeInterval

function constructGame() {
	board = Chessboard('myBoard', {
		pieceTheme: '{piece}.png',
		draggable: true,
		position: 'start',
		onDragStart: onDragStart,
		onDrop: onDrop,
		onSnapEnd: onSnapEnd
	})
	game = new Chess()
}

function destroyGame() {
	inGame = false
	clearInterval(recordTimeInterval)
	TIME_ELEMENT.innerHTML = getTime(0)
	board.destroy()
}

function restartGame() {
	destroyGame()
	constructGame()
}

function recordTime() {
	time = (new Date()) - startTime
	TIME_ELEMENT.innerHTML = getTime(time)
}

function startGame() {
	inGame = true
	startTime = new Date()
	recordTimeInterval = setInterval(recordTime, 1)
}

function endGame(ending) {
	inGame = false
	clearInterval(recordTimeInterval)
	recordTime()

	let message
	switch (ending) {
		case 2:
			if (time < bestTime) {
				bestTime = time
				BEST_ELEMENT.innerHTML = getTime(bestTime)
				localStorage.setItem('best', bestTime.toFixed())
			}
			message = 'You win! Time: ' + getTime(time) + ' Best: ' + getTime(bestTime)
			break;
		case 1:
			message = 'Tie!'
			break;
		default:
			message = 'Loser!'
			break;
	}
	alert(message)
}

function onDragStart(source, piece, position, orientation) {
	// do not pick up pieces if the game is over
	if (game.game_over())
		return false

	// record game start
	if (!inGame)
		startGame()

	// only pick up pieces for White
	if (piece.search(/^b/) !== -1)
		return false
}

function makeRandomMove() {
	var possibleMoves = game.moves()

	// game over
	if (possibleMoves.length === 0)
		return

	var randomIdx = Math.floor(Math.random() * possibleMoves.length)
	game.move(possibleMoves[randomIdx])
	board.position(game.fen())
}

function onDrop(source, target) {
	// see if the move is legal
	var move = game.move({
		from: source,
		to: target,
		promotion: 'q' // NOTE: always promote to a queen for simplicity
	})

	// illegal move
	if (move === null) return 'snapback'

	if (inGame && game.game_over())
		endGame(game.in_checkmate() ? 2 : 1)

	// make random legal move for black
	makeRandomMove()

	if (inGame && game.game_over())
		endGame(game.in_checkmate() ? 0 : 1)
}

// update the board position after the piece snap
// for castling, en passant, pawn promotion
function onSnapEnd() {
	board.position(game.fen())
}

constructGame()